package com.example.spring_boot_login.controller;

import com.example.spring_boot_login.model.ResponseBodyMessage;
import com.example.spring_boot_login.model.User;
import com.example.spring_boot_login.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public ResponseBodyMessage<User> login(String username, String password, HttpServletRequest request) {
        System.out.println(username);
        System.out.println(password);
        User user = userService.login(username, password);
        if (user == null) {
            log.info("用户名：" + username + " ；密码：" + password + " 登录失败！");
            return new ResponseBodyMessage<User>(-1, "登录失败！", null);
        }else {
            HttpSession session = request.getSession(true);
            session.setAttribute("user", user);
            user.setPassword("");
            return new ResponseBodyMessage<>(0,"登录成功！", user);
        }
    }


    @RequestMapping("/info")
    public ResponseBodyMessage<String> info(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            log.info("当前未有登录用户！");
            return new ResponseBodyMessage<String>(-1, "当前未有用户登录！", null);
        }else {
            User user = (User)session.getAttribute("user");
            return new ResponseBodyMessage<String>(0, "获取用户信息成功！", user.getUsername());
        }
    }
}
